//
//  AppDelegate.m
//  WSL
//
//  Created by CJ on 2017/9/25.
//  Copyright © 2017年 sanjuetech. All rights reserved.
//


// YYKit 里修改了YYTextLayout 538行， YYLabel 127行

#import "AppDelegate.h"
#import "SJMyZeroViewController.h"
#import "SJDiscoveryViewController.h"
#import "SJPersonalViewController.h"
#import "SJMessageListViewController.h"
#import "SJDiscoveryContainerViewController.h"

#import <YTKNetwork/YTKNetwork.h>
#import "SJUrlArgumentsFilter.h"

#import "YALTabBarItem.h"
#import "YALFoldingTabBarController.h"
#import "YALAnimatingTabBarConstants.h"

#import <CYLTabBarController/CYLTabBarController.h>

#import <ShareSDK/ShareSDK.h>
#import <ShareSDKConnector/ShareSDKConnector.h>

#import <TencentOpenAPI/TencentOAuth.h>
#import <TencentOpenAPI/QQApiInterface.h>

#import "WXApi.h"
#import "WeiboSDK.h"

// 引入JPush功能所需头文件
#import "JPUSHService.h"
// iOS10注册APNs所需头文件
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#import <UserNotifications/UserNotifications.h>
#endif


#import "SJPushTagsApi.h"

#import <UMCommon/UMCommon.h>           // 公共组件是所有友盟产品的基础组件，必选
#import <UMAnalytics/MobClick.h>        // 统计组件


#import <EAIntroView/EAIntroView.h>

@interface AppDelegate () <JPUSHRegisterDelegate, CLLocationManagerDelegate>

@property (nonatomic, strong) CLLocationManager *locationmgr;
@property (nonatomic, strong) CLGeocoder *geocoder;
@property (nonatomic, copy) NSString *city;
@property (nonatomic, copy) NSString *subLocality;
@property (nonatomic, copy) NSString *province;
@property (nonatomic, copy) NSString *registrationID;


@property (nonatomic, strong) CYLTabBarController *tabBarController;

@end

@implementation AppDelegate

- (void)setupRequestFilters {
    
    [SVProgressHUD setDefaultStyle:SVProgressHUDStyleDark];
//    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeGradient];

    YTKNetworkConfig *config = [YTKNetworkConfig sharedConfig];
    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"from"] = @"ios";
    parameters[@"sv"] = [UIApplication sharedApplication].appVersion;
    parameters[@"ov"] = [[UIDevice currentDevice] systemVersion];
    parameters[@"rs"] = [NSString stringWithFormat:@"%.0f*%.0f", 2*SJScreenH, 2*SJScreenW];
    parameters[@"model"] = [[UIDevice currentDevice] machineModelName];
    
    SJUrlArgumentsFilter *urlFilter = [SJUrlArgumentsFilter filterWithArguments:parameters];
    config.baseUrl = SJCommonURL;
    [config addUrlFilter:urlFilter];
    
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    
    // 0.配置网络
    [self setupRequestFilters];
    
    // 1.创建窗口
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    
    // 2.创建根控制器
    
    [self setupViewControllers];
    
    self.window.rootViewController = self.tabBarController;
    
    // 3.显示窗口
    [self.window makeKeyAndVisible];
    
    // 显示欢迎页
    if ([self hasNewVersion]) {
        [self welcomeView];
    }
        
    // 定位
    [self location];
    
    // shareSDK 注册方法
    [self _registerShare];
    
    // 友盟
    [self registerUM];
    
    // 添加初始化JPUSH代码
    [self registerJPUSHWithOptions:launchOptions];
    
    return YES;
}


- (void)welcomeView {
    
    EAIntroPage *page1 = [EAIntroPage page];
    page1.bgImage = [UIImage imageNamed:@"welcome_pic_1"];
    
    EAIntroPage *page2 = [EAIntroPage page];
    page2.bgImage = [UIImage imageNamed:@"welcome_pic_2"];
    
    EAIntroPage *page3 = [EAIntroPage page];
    page3.bgImage = [UIImage imageNamed:@"welcome_pic_3"];
    
    EAIntroPage *page4 = [EAIntroPage page];
    page4.bgImage = [UIImage imageNamed:@"welcome_pic_4"];
    
    EAIntroView *intro = [[EAIntroView alloc] initWithFrame:self.window.bounds andPages:@[page1, page2, page3, page4]];
    intro.skipButtonAlignment = EAViewAlignmentRight;
    intro.skipButtonY = SJLayoutFrame(80);
    intro.pageControl.hidden= YES;
    intro.showSkipButtonOnlyOnLastPage = YES;
    [intro.skipButton setTitle:@">>>" forState:UIControlStateNormal];
    
//    [intro setDelegate:self];
    
    [intro showInView:self.window animateDuration:0.3];
    
}

- (BOOL)hasNewVersion {
    
    // 1、 取出沙盒中存储的上次使用软件的版本号
    NSString *key = @"CFBundleShortVersionString";
    NSString *lastVersion = [SJUserDefaults stringForKey:key];
    
    // 2、获得当前软件的版本号
    NSString *currentVersion = [UIApplication sharedApplication].appVersion;;
    
    // 3、判断版本号
    if ([lastVersion isEqualToString:currentVersion]) {// 旧版本
        return NO;
    } else { // 新版本
        
        // 存储新版本
        [SJUserDefaults setObject:currentVersion forKey:key];
        [SJUserDefaults synchronize];
        return YES;
    }
}

- (void)setupViewControllers {
//
//    // 探索空间
//    SJDiscoveryViewController *discoveryVC = [SJDiscoveryViewController new];
//    discoveryVC.isDiscovery = @"1";
//    SJNavigationController *discoveryNav = [[SJNavigationController alloc] initWithRootViewController:discoveryVC];
    
    
    // 探索空间
    SJDiscoveryContainerViewController *discoveryVC = [SJDiscoveryContainerViewController new];
    SJNavigationController *discoveryNav = [[SJNavigationController alloc] initWithRootViewController:discoveryVC];
    
    // 思藏
    SJMyZeroViewController *myZeroVC = [SJMyZeroViewController new];
    SJNavigationController *myZeroNav = [[SJNavigationController alloc] initWithRootViewController:myZeroVC];
    
    
    // 消息
    SJMessageListViewController *messageVC = [SJMessageListViewController new];
    SJNavigationController *messageNav = [[SJNavigationController alloc] initWithRootViewController:messageVC];
    
    
    // 个人中心
    SJPersonalViewController *personalVC = [SJPersonalViewController new];
    personalVC.isMe = YES;
    SJNavigationController *personalNav = [[SJNavigationController alloc] initWithRootViewController:personalVC];
    
    
    CYLTabBarController *tabBarController = [[CYLTabBarController alloc] init];
    [self customizeTabBarForController:tabBarController];
    
    tabBarController.tabBarHeight = SJLayoutFrame(80);
    [tabBarController hideTabBadgeBackgroundSeparator];
    
    [[UITabBar appearance] setBackgroundImage:[[UIImage alloc] init]];
    [[UITabBar appearance] setBackgroundColor:[UIColor clearColor]];
    [[UITabBar appearance] setShadowImage:[[UIImage alloc] init]];
    
    [tabBarController setViewControllers:@[ myZeroNav, discoveryNav, messageNav, personalNav ]];
    self.tabBarController = tabBarController;
    tabBarController.selectedIndex = 1;
}

/*
 *
 在`-setViewControllers:`之前设置TabBar的属性，
 *
 */
- (void)customizeTabBarForController:(CYLTabBarController *)tabBarController {
    
    NSDictionary *dict0 = @{
                            CYLTabBarItemImage : @"common_tab_icon_sicang_nor",
                            CYLTabBarItemSelectedImage : @"common_tab_icon_sicang_sel",
                            };
    
    NSDictionary *dict1 = @{
                            CYLTabBarItemImage : @"common_tab_icon_explore_nor",
                            CYLTabBarItemSelectedImage : @"common_tab_icon_explore_sel",
                            };
    
    NSDictionary *dict2 = @{
                            CYLTabBarItemImage : @"common_tab_icon_message_nor",
                            CYLTabBarItemSelectedImage : @"common_tab_icon_message_sel",
                            };
    
    NSDictionary *dict3 = @{
                            CYLTabBarItemImage : @"common_tab_icon_mine_nor",
                            CYLTabBarItemSelectedImage : @"common_tab_icon_mine_sel",
                            };
    
    
    NSArray *tabBarItemsAttributes = @[ dict0, dict1, dict2, dict3 ];
    tabBarController.tabBarItemsAttributes = tabBarItemsAttributes;
}

- (void)location {
    
    self.locationmgr = [CLLocationManager new];
    if ([self.locationmgr respondsToSelector:@selector(requestWhenInUseAuthorization)]) {
        [self.locationmgr requestWhenInUseAuthorization];
    }
    self.locationmgr.delegate = self;
    self.geocoder = [[CLGeocoder alloc] init];
    [self.locationmgr startUpdatingLocation];
}

#pragma mark - 友盟
- (void)registerUM {
    
    [UMConfigure initWithAppkey:SJUM_KEY channel:@"App Store"];
    
    // 统计组件配置
    [MobClick setScenarioType:E_UM_NORMAL];
    
    // [UMConfigure setEncryptEnabled:YES]; // optional: 设置加密传输, 默认NO.
//    [UMConfigure setLogEnabled:YES]; // 开发调试时可在console查看友盟日志显示，发布产品必须移除。

}

#pragma mark - CLLocationManagerDelegate

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations {
    
    CLLocation * location = locations.lastObject;
    
    WeakSelf;
    [self.geocoder reverseGeocodeLocation:location completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        
        if (placemarks.count > 0) {
            
            CLPlacemark *placemark = [placemarks objectAtIndex:0];
            
            // 获取省份
            weakSelf.province = placemark.administrativeArea;
            
            // 获取城市
            weakSelf.city = placemark.locality;
            
            // 获取城市
            weakSelf.subLocality = placemark.subLocality;
            
            if (!weakSelf.province) {
                weakSelf.province = weakSelf.city;
            }
            
            if (!weakSelf.subLocality) {
                weakSelf.province = weakSelf.city;
            }
            
            [weakSelf pushTags];
            
        } else if (error == nil && [placemarks count] == 0) {
            SJLog(@"No results were returned.");
        } else if (error != nil){
            SJLog(@"An error occurred = %@", error);
        }
    }];
    
    [self.locationmgr stopUpdatingLocation];
}

// 设置 tags & registrationID；
- (void)pushTags {
    
    if (self.city && self.province && self.subLocality && self.registrationID) {
        
        NSSet *tags = [[NSSet alloc] initWithArray:@[
                                                     self.city,
                                                     self.province,
                                                     self.subLocality
                                                     ]];
        
        WeakSelf;
        [JPUSHService setTags:tags completion:^(NSInteger iResCode, NSSet *iTags, NSInteger seq) {
            
            if (iResCode == 0) {
                
                NSSortDescriptor *sd = [[NSSortDescriptor alloc] initWithKey:nil ascending:YES];
                NSArray *sortDescriptors = [NSArray arrayWithObjects:sd, nil];
                NSArray *tagsArray = [iTags sortedArrayUsingDescriptors:sortDescriptors];
                
                NSString *tagsJson = [tagsArray jsonStringEncoded];
                
                // 1.拼接参数
                NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
                parameters[@"token"] = [SJUserDefaults objectForKey:SJToken];
                parameters[@"tags"] = tagsJson;
                parameters[@"registration_id"] = weakSelf.registrationID;
                
                SJPushTagsApi *api = [[SJPushTagsApi alloc] initWithParameters:parameters];
                [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
                    
                    if ([api.responseObject[@"result"][@"err"] intValue] == 0) {
                        
                    }
                    
                } failure:^(YTKBaseRequest *request) {
                }];
                
            }
            
        } seq:1];

    }
    
    NSString *alias = [SJUserDefaults objectForKey:SJToken];
    
    if (alias) {
       
        [JPUSHService setAlias:alias completion:^(NSInteger iResCode, NSString *iAlias, NSInteger seq) {
            
            SJLog(@"iResCode=== %ld", (long)iResCode);
        } seq:1];
    }
}


#pragma mark - JPUSH

- (void)registerJPUSHWithOptions:(NSDictionary *)launchOptions  {
    
    // 3.0.0及以后版本注册可以这样写，也可以继续用旧的注册方式
    JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
    entity.types = JPAuthorizationOptionAlert | JPAuthorizationOptionBadge | JPAuthorizationOptionSound;
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
        //可以添加自定义categories
        //    if ([[UIDevice currentDevice].systemVersion floatValue] >= 10.0) {
        //      NSSet<UNNotificationCategory *> *categories;
        //      entity.categories = categories;
        //    }
        //    else {
        //      NSSet<UIUserNotificationCategory *> *categories;
        //      entity.categories = categories;
        //    }
    }
    [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
    
    //如不需要使用IDFA，advertisingIdentifier 可为nil
    [JPUSHService setupWithOption:launchOptions appKey:SJJPushAppKey
                          channel:@"App Store"
                 apsForProduction:isProduction
            advertisingIdentifier:nil];
    
    //2.1.9版本新增获取registration id block接口。。
    WeakSelf;
    [JPUSHService registrationIDCompletionHandler:^(int resCode, NSString *registrationID) {
        if(resCode == 0){
            SJLog(@"registrationID获取成功：%@", registrationID);
            weakSelf.registrationID = registrationID;
            
            [weakSelf pushTags];
        }
        else{
            SJLog(@"registrationID获取失败，code：%d", resCode);
        }
    }];
    
}

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    SJLog(@"%@", [NSString stringWithFormat:@"Device Token: %@", deviceToken]);
    [JPUSHService registerDeviceToken:deviceToken];
}

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    SJLog(@"did Fail To Register For Remote Notifications With Error: %@", error);
}

#pragma mark- JPUSHRegisterDelegate

// iOS 10 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler {
    // Required
    NSDictionary * userInfo = notification.request.content.userInfo;
    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
    }
    completionHandler(UNNotificationPresentationOptionAlert); // 需要执行这个方法，选择是否提醒用户，有Badge、Sound、Alert三种类型可以选择设置
}

// iOS 10 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler {
    // Required
    NSDictionary * userInfo = response.notification.request.content.userInfo;
    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
    }
    completionHandler();  // 系统要求执行这个方法
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    
    // Required, iOS 7 Support
    [JPUSHService handleRemoteNotification:userInfo];
    completionHandler(UIBackgroundFetchResultNewData);
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    
    // Required,For systems with less than or equal to iOS6
    [JPUSHService handleRemoteNotification:userInfo];
}





#pragma mark - shareSDK

- (void)_registerShare
{
    //平台注册
    NSArray *platforems = @[
                            @(SSDKPlatformSubTypeWechatSession),
                            @(SSDKPlatformSubTypeWechatTimeline),
                            @(SSDKPlatformSubTypeQQFriend),
                            @(SSDKPlatformTypeSinaWeibo)
                            ];
    [ShareSDK registerActivePlatforms:platforems
                             onImport:^(SSDKPlatformType platformType) {
                                 switch (platformType) {
                                         
                                     case SSDKPlatformTypeQQ:
                                         [ShareSDKConnector connectQQ:[QQApiInterface class] tencentOAuthClass:[TencentOAuth class]];
                                         break;
                                     case SSDKPlatformTypeWechat:
                                         [ShareSDKConnector connectWeChat:[WXApi class] delegate:nil];
                                         break;
                                         
                                     case SSDKPlatformTypeSinaWeibo:
                                         [ShareSDKConnector connectWeibo:[WeiboSDK class]];
                                         break;
                                         
                                     default:
                                         break;
                                 }
                             }
                      onConfiguration:^(SSDKPlatformType platformType, NSMutableDictionary *appInfo) {
                          switch (platformType)
                          {
                              case SSDKPlatformTypeQQ:
                                  [appInfo SSDKSetupQQByAppId:SJQQ_ID
                                                       appKey:SJQQ_KEY
                                                     authType:SSDKAuthTypeBoth];
                                  break;
                                  
                              case SSDKPlatformTypeWechat:
                                  [appInfo SSDKSetupWeChatByAppId:SJWX_ID
                                                        appSecret:SJWX_SECRET];
                                  break;
                                  
                              case SSDKPlatformTypeSinaWeibo:
                                  //设置新浪微博应用信息,其中authType设置为使用SSO＋Web形式授权
                                  [appInfo SSDKSetupSinaWeiboByAppKey:SJWB_KEY
                                                            appSecret:SJWB_SECRET
                                                          redirectUri:@"http://www.sanjuetech.com/"
                                                             authType:SSDKAuthTypeBoth];
                                  break;
                                  
                              default:
                                  break;
                          }
                      }];
    
}

//
//
//- (YALFoldingTabBarController *)setupTabBarController {
//
//    YALFoldingTabBarController *tabBarController = [YALFoldingTabBarController new];
//
//    //prepare leftBarItems
//    YALTabBarItem *item1 = [[YALTabBarItem alloc] initWithItemImage:[UIImage imageNamed:@"my_nor"]
//                                                      selectedImage:[UIImage imageNamed:@"my_sel"]
//                                                      leftItemImage:nil
//                                                     rightItemImage:nil];
//
//
//    YALTabBarItem *item2 = [[YALTabBarItem alloc] initWithItemImage:[UIImage imageNamed:@"explore_nor"]
//                                                      selectedImage:[UIImage imageNamed:@"explore_sel"]
//                                                      leftItemImage:nil
//                                                     rightItemImage:nil];
//
//    tabBarController.leftBarItems = @[item1, item2];
//
//    //prepare rightBarItems
//    YALTabBarItem *item3 = [[YALTabBarItem alloc] initWithItemImage:[UIImage imageNamed:@"message_nor"]
//                                                      selectedImage:[UIImage imageNamed:@"message_sel"]
//                                                      leftItemImage:nil
//                                                     rightItemImage:nil];
//
//
//    YALTabBarItem *item4 = [[YALTabBarItem alloc] initWithItemImage:[UIImage imageNamed:@"profile_nor"]
//                                                      selectedImage:[UIImage imageNamed:@"profile_sel"]
//                                                      leftItemImage:nil
//                                                     rightItemImage:nil];
//
//    tabBarController.rightBarItems = @[item3, item4];
//
//    tabBarController.centerButtonImage = [UIImage imageNamed:@"btn_floating_menu"];
//
//    tabBarController.selectedIndex = 0;
//
//
//    //customize tabBarView
//    tabBarController.tabBarView.extraTabBarItemHeight = YALExtraTabBarItemsDefaultHeight;
//    tabBarController.tabBarView.offsetForExtraTabBarItems = YALForExtraTabBarItemsDefaultOffset;
//    tabBarController.tabBarViewHeight = YALTabBarViewDefaultHeight;
//    tabBarController.tabBarView.tabBarViewEdgeInsets = YALTabBarViewHDefaultEdgeInsets;
//    tabBarController.tabBarView.tabBarItemsEdgeInsets = YALTabBarViewItemsDefaultEdgeInsets;
//
//    tabBarController.tabBarView.tabBarColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"menu_bg"]];
//    tabBarController.tabBarView.dotColor = [UIColor clearColor];
//    tabBarController.tabBarView.state = YALTabBarStateExpanded;
//
//    return tabBarController;
//}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
    application.applicationIconBadgeNumber = 0;
    
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    
    // 监听剪切板
    [self getPasteboard];
}

- (void)getPasteboard {
    
//    UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
//    
//    NSString *str = pasteboard.string;
//    
//    SJLog(@"strstrstrstrstr------------%@", str);
    
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}


@end
